<?php
/**
 * @title 75. 颜色分类 - 原地操作数组
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param Integer[] $nums
     * @return NULL
     */
    function sortColors(&$nums) {
        /**
         * @since 2020-08-05 转移蓝色球数量
         */
        $blueCount = 0;

        /**
         * @since 2020-08-05 迭代
         */
        for ($k=0, $i=0, $len=count($nums); $i<$len; $i++){
            /**
             * @since 2020-08-05 红色转移到数组头部
             */
            if($nums[$k] == 0){
                unset($nums[$k]);
                array_unshift($nums, 0);
                $k = $k+1-$blueCount;
                $blueCount=0;
            } elseif ($nums[$k] == 2){
                /**
                 * @since 2020-08-05 蓝色转移到数组尾部
                 */
                unset($nums[$k]);
                $nums[] = 2;
                $blueCount++;
                $k++;
            } else {
                /**
                 * @since 2020-08-05 白色不操作
                 */
                $k++;
            }
        }

        /**
         * @return
         */
        return $nums;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.05_2.php
 */
$datas = [
    [2,0,2,1,1,0],
    [1,2,2,2,2,0,0,0,1,1],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->sortColors($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
